/*
 * Copyright (C) 2011 mAPPn.Inc
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mol.market.ui_v4;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.*;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.mol.market.Constants;
import com.mol.market.R;
import com.mol.market.Session;
import com.mol.market.common.network.ApiAsyncTask;
import com.mol.market.common.network.ApiAsyncTask.ApiRequestListener;
import com.mol.market.common.network.MarketAPI;
import com.mol.market.common.util.ImageUtils;
import com.mol.market.common.util.Utils;
import com.mol.market.common.vo.RecommendTopic;
import com.mol.market.common.widget.LoadingDrawable;
import com.mol.market.ui.RecommendActivity;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 已关注达人推荐专题
 * 
 * 
 * @author andrew.wang
 * @date   2011-12-21
 * @since  Version 0.9
 */
public class FollowedRecommendFragment extends SherlockFragment implements OnGroupClickListener,
        OnChildClickListener, ApiRequestListener, OnClickListener {

    // Loading
    private FrameLayout mLoading;
    private ProgressBar mProgress;
    private TextView mNoData;
    private ExpandableListView mList;
    private ExpandableListAdapter mAdapter;
    private Session mSession;
    private SherlockFragmentActivity mActivity;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.activity_followed_layout, container, false);

        mList = (ExpandableListView) v.findViewById(R.id.followed_list);
        mList.setOnGroupClickListener(this);
        mList.setOnChildClickListener(this);

        mLoading = (FrameLayout) v.findViewById(R.id.loading);
        mProgress = (ProgressBar) mLoading.findViewById(R.id.progressbar);
        mProgress.setIndeterminateDrawable(new LoadingDrawable(mActivity));
        mProgress.setVisibility(View.VISIBLE);
        mNoData = (TextView) mLoading.findViewById(R.id.no_data);
        mNoData.setOnClickListener(this);
        mList.setEmptyView(mLoading);

        MarketAPI.getFollowedRecommend(mActivity, this);
        return v;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mActivity = getSherlockActivity();
        mSession = Session.get(mActivity);
    }
    
    @SuppressWarnings("unchecked")
    @Override
    public void onSuccess(int method, Object obj) {

        if (method == MarketAPI.ACTION_GET_FOLLOWED_RECOMMEND) {

            HashMap<String, Object> result = (HashMap<String, Object>) obj;
            int totalSize = (Integer) result.get(Constants.KEY_TOTAL_SIZE);
            if (totalSize > 0) {
                ArrayList<HashMap<String, Object>> data = (ArrayList<HashMap<String, Object>>) result
                        .get(Constants.KEY_RECOMMEND_LIST);
                mAdapter = new ExpandableListAdapter(mActivity,
                        data);
                mList.setAdapter(mAdapter);
            } else {
                // 没有关注任何达人
                mNoData.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.no_followed_master,
                        0, 0);
                mNoData.setCompoundDrawablePadding(10);
                mNoData.setText(R.string.label_no_followed_master);
                mNoData.setVisibility(View.VISIBLE);
                mProgress.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onError(int method, int statusCode) {
        if (statusCode == ApiAsyncTask.BUSINESS_ERROR) {
            // TODO 没有数据
        } else {
            // 超时
            mNoData.setVisibility(View.VISIBLE);
            mProgress.setVisibility(View.GONE);
        }
    }
    
    @Override
    public void onClick(View paramView) {
        if (paramView.getId() == R.id.no_data) {
            // 重试
            mProgress.setVisibility(View.VISIBLE);
            mNoData.setVisibility(View.GONE);
            MarketAPI.getFollowedRecommend(mActivity, this);
            return;
        }
    }
    
    public class ExpandableListAdapter extends BaseExpandableListAdapter {
        
        private Context mContext;
        private ArrayList<HashMap<String, Object>> mDataSource;
        private LayoutInflater mInflater;
        
        public ExpandableListAdapter(Context context, ArrayList<HashMap<String, Object>> data) {
            mContext = context;
            mDataSource = data;
            mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        

        @SuppressWarnings("unchecked")
        public Object getChild(int groupPosition, int childPosition) {

            HashMap<String, Object> groupItem = mDataSource.get(groupPosition);
            ArrayList<HashMap<String, Object>> children = (ArrayList<HashMap<String, Object>>) 
                    groupItem.get(Constants.KEY_PRODUCT_LIST);
            if (children != null) {
                return children.get(childPosition);
            }
            return null;
        }

        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }

        @SuppressWarnings("unchecked")
        public int getChildrenCount(int groupPosition) {

            HashMap<String, Object> groupItem = mDataSource.get(groupPosition);
            ArrayList<HashMap<String, Object>> children = (ArrayList<HashMap<String, Object>>)
                    groupItem.get(Constants.KEY_PRODUCT_LIST);
            if (children != null) {
                return children.size();
            }
            return 0;
        }
        

        public Object getGroup(int groupPosition) {
            return mDataSource.get(groupPosition);
        }

        public int getGroupCount() {
            return mDataSource.size();
        }

        public long getGroupId(int groupPosition) {
            return groupPosition;
        }


        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                ViewGroup parent) {
            
            View v;
            if (convertView == null) {
                v = newGroupView(parent);
            } else {
                v = convertView;
            }
            
            bindGroupView(groupPosition, isExpanded, v);
            return v;
        }
        
        /*
         * Create new view object and cache some views associated with it
         */
        private View newGroupView(ViewGroup parent) {
            View v = mInflater.inflate(R.layout.activity_followed_item, parent, false);

            int length = toGroup.length;
            final View[] holder = new View[length];

            for (int i = 0; i < length; i++) {
                holder[i] = v.findViewById(toGroup[i]);
            }

            v.setTag(holder);
            return v;
        }
        
        private final int[] toGroup = new int[] { R.id.iv_user_icon, R.id.topic_name,
                R.id.update_info, R.id.btn_update, R.id.indicator, R.id.open_indicator };
        
        
        /*
         * Bind data object to the view
         */
        private void bindGroupView(final int position, final boolean isExpanded, View root) {
            
            final HashMap<String, Object> groupItem = mDataSource.get(position);
            if (groupItem == null) {
                return;
            }
            
            final View[] holder = (View[]) root.getTag();
            final int count = toGroup.length;
            
            for (int i = 0; i < count; i++) {

                final View v = holder[i];
                final int id = v.getId();
                if (id == R.id.open_indicator) {
                    
                    // 打开指示器
                    if (isExpanded) {
                        v.setVisibility(View.VISIBLE);
                    } else {
                        v.setVisibility(View.GONE);
                    }
                } else if(id == R.id.iv_user_icon) {

                  ImageUtils.download(mContext, (String) groupItem.get(Constants.KEY_ICON_URL),
                      (ImageView) v, R.drawable.default_user_big, false,
                      false);
                } else if(id == R.id.topic_name) {
                    
                    ((TextView)v).setText((String) groupItem.get(Constants.KEY_RECOMMEND_NAME));
                } else if(id == R.id.update_info) {
                    
                    String userName = (String) groupItem.get(Constants.KEY_USER);
                    if (!TextUtils.isEmpty(userName)) {
                        SpannableStringBuilder text = new SpannableStringBuilder(userName);
                        TextAppearanceSpan span = new TextAppearanceSpan(mContext,
                                R.style.text_style_1f);
                        int length = userName.length();
                        text.setSpan(span, 0, length, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        
                        int unread = (Integer) groupItem.get(Constants.KEY_UNREAD);
                        if (unread > 0) {
                            text.append(mContext.getString(R.string.label_have_unread,
                                    String.valueOf(unread)));
                        } else {
                            text.append(mContext.getString(R.string.label_no_unread));
                        }
                        TextAppearanceSpan span2 = new TextAppearanceSpan(mContext,
                                R.style.text_style_1c);
                        text.setSpan(span2, length, text.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
                        ((TextView) v).setText(text);
                    } else {
                        ((TextView) v).setText((String) groupItem.get(Constants.KEY_UPDATE_TIME));
                    }
                    
                } else if(id == R.id.btn_update) {
                    
                    int unread = (Integer) groupItem.get(Constants.KEY_UNREAD);
                    if (unread > 0) {
                        // 拥有更新产品
                        final TextView btn = (TextView) v;
                        if (isExpanded) {
                            btn.setBackgroundResource(R.drawable.group_expand);
                        } else {
                            btn.setBackgroundResource(R.drawable.group_collapse);
                        }
                        btn.setText(R.string.read_new);
                        btn.setVisibility(View.VISIBLE);
                        btn.setClickable(true);
                        btn.setOnClickListener(new OnClickListener() {
                            
                            @Override
                            public void onClick(View v) {
                                
                                if (isExpanded) {
                                    mList.collapseGroup(position);
                                } else {
                                    // XXX 优化性能
                                    Utils.trackEvent(mActivity, Constants.GROUP_4,
                                            Constants.EVENT_CLICK_NEWS);
                                    String id = (String) groupItem.get(Constants.KEY_ID);
                                    MarketAPI.markFollowedRead(mContext, id,
                                            FollowedRecommendFragment.this);
                                    mList.expandGroup(position);
                                }
                            }
                        });
                    } else {
                        ((TextView) v).setVisibility(View.INVISIBLE);
                    }
                } else if(id == R.id.indicator) {
                    
                    int unread = (Integer) groupItem.get(Constants.KEY_UNREAD);
                    if (unread > 0) {
                        // 拥有更新产品
                        ((ImageView) v).setVisibility(View.GONE);
                    } else {
                        ((ImageView) v).setVisibility(View.VISIBLE);
                    }
                    
                }
            }
        }
        

        public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
                View convertView, ViewGroup parent) {
            
            View v;
            if (convertView == null) {
                v = newChildView(parent);
            } else {
                v = convertView;
            }
            
            bindChildView(groupPosition, childPosition, v);
            return v;
        }
        
        private final int[] toChild = new int[] { R.id.iv_logo, R.id.tv_name, R.id.tv_category,
                R.id.tv_size, R.id.tv_description };
        
        /*
         * Create new view object and cache some views associated with it
         */
        private View newChildView(ViewGroup parent) {
            
            View v = mInflater.inflate(R.layout.master_recommend_list_item, parent, false);

            int length = toChild.length;
            final View[] holder = new View[length];

            for (int i = 0; i < length; i++) {
                holder[i] = v.findViewById(toChild[i]);
            }

            v.setTag(holder);
            return v;
        }
        
        /*
         * Bind data object to the view
         */
        @SuppressWarnings("unchecked")
        private void bindChildView(int groupPosition, int childPosition, View root) {
            
            final HashMap<String, Object> groupItem = mDataSource.get(groupPosition);
            if (groupItem == null) {
                return;
            }
            final ArrayList<HashMap<String, Object>> children = 
                (ArrayList<HashMap<String, Object>>)groupItem.get(Constants.KEY_PRODUCT_LIST);
            if (children == null || children.size() <= 0) {
                return;
            }
            final HashMap<String, Object> child = children.get(childPosition);
            
            final View[] holder = (View[]) root.getTag();
            final int count = toChild.length;
            
            for (int i = 0; i < count; i++) {

                final View v = holder[i];
                final int id = v.getId();
                if (id == R.id.iv_logo) {

                    ImageUtils.download(mContext,
                            (String) child.get(Constants
                                .KEY_PRODUCT_ICON_URL), (ImageView) v, false);
                } else if (id == R.id.tv_name) {

                    ((TextView) v).setText((String) child.get(Constants.KEY_PRODUCT_NAME));
                } else if (id == R.id.tv_category) {

                    ((TextView) v).setText((String) child.get(Constants.KEY_PRODUCT_SUB_CATEGORY));

                } else if (id == R.id.tv_size) {

                    ((TextView) v).setText((String) child.get(Constants.KEY_PRODUCT_SIZE));
                } else if (id == R.id.tv_description) {

                    ((TextView) v).setText((String) child
                            .get(Constants.KEY_PRODUCT_SHORT_DESCRIPTION));
                }
            }
        }
        

        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public boolean hasStableIds() {
            return true;
        }

    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
        
        HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getGroup(groupPosition);
        RecommendTopic mTopic = new RecommendTopic();
        mTopic.id = (String) item.get(Constants.KEY_ID);
        mTopic.icon = (String) item.get(Constants.KEY_ICON_URL);
        mTopic.title = (String) item.get(Constants.KEY_RECOMMEND_NAME);
        mTopic.description = (String) item.get(Constants.KEY_DESCRIPTION);
        mTopic.up = Utils.getInt((String) item.get(Constants.KEY_LIKE));
        mTopic.down = Utils.getInt((String) item.get(Constants.KEY_DISLIKE));
        mTopic.experience = (String) item.get(Constants.KEY_EXPERIENCE);
        mTopic.user = (String) item.get(Constants.KEY_USER);
        mTopic.fans = Utils.getInt((String) item.get(Constants.KEY_FANS));
        
        Intent i = new Intent(mActivity, RecommendActivity.class);
        i.putExtra(Constants.EXTRA_RECOMMEND_DETAIL, mTopic);
        startActivityForResult(i, 0);
        
        return true;
    }

    @SuppressWarnings("unchecked")
    @Override
    public boolean onChildClick(ExpandableListView parent, View v,
            int groupPosition, int childPosition, long id) {
        
        HashMap<String, Object> item = (HashMap<String, Object>) mAdapter.getGroup(groupPosition);
        ArrayList<HashMap<String, Object>> products = (ArrayList<HashMap<String, Object>>) item
                .get(Constants.KEY_PRODUCT_LIST);
        
        HashMap<String, Object> product = products.get(childPosition);
        String packageName = (String) product.get(Constants.KEY_PRODUCT_PACKAGE_NAME);
        // 点击去详细页
        Intent detailIntent = new Intent(mActivity, ProductDetailActivity.class);
        detailIntent.putExtra(Constants.EXTRA_PRODUCT_NAME,
                (String) item.get(Constants.KEY_PRODUCT_NAME));
        detailIntent.putExtra(Constants.EXTRA_PACKAGE_NAME, packageName);
        startActivity(detailIntent);
        return true;
    }

}
